package com.zzh.h265toupin.sockets

import android.util.Log
import android.widget.Toast
import org.java_websocket.client.WebSocketClient
import org.java_websocket.handshake.ServerHandshake
import java.lang.Exception
import java.net.URI
import java.net.URL
import java.nio.ByteBuffer

//拉流端作为客户端
class SocketPullClient(
    val url: String,
    private val socketCallback: (data: ByteArray?) -> Unit

) {

    private var client: MysocketClient? = null

    private var connectCallback: ((connected: Boolean) -> Unit)? = null

    fun setConnectCallback(connectCallback: (connected: Boolean) -> Unit) {
        this.connectCallback = connectCallback
    }

    fun start() {
        try {
            client = MysocketClient(URI.create(url))
            client!!.connect()
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }

    fun close() {
        client?.close()
        client = null
    }


    inner class MysocketClient(serverUri: URI) : WebSocketClient(serverUri) {
        override fun onOpen(handshakedata: ServerHandshake?) {
            Log.d("TAG_SocketPullClient", "client建立了连接..$url")
            connectCallback?.invoke(true)
        }

        override fun onMessage(message: String?) {
        }

        override fun onClose(code: Int, reason: String?, remote: Boolean) {
            Log.d("TAG_SocketPullClient", "client断开连接 -- $code: $reason , remove:$remote")
            connectCallback?.invoke(false)
        }

        override fun onError(ex: Exception?) {

        }

        override fun onMessage(bytes: ByteBuffer?) {
            bytes ?: return
            val frame = ByteArray(bytes.remaining())
            bytes.get(frame)
            socketCallback.invoke(frame)
        }

    }
}